use std::str::FromStr;

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    if to_base < 2 || to_base > 16 {
        panic!("Target base must be between 2 and 16");
    }

    // 解析输入字符串，获取数字和原始进制
    let parts: Vec<&str> = num_str.split('(').collect();
    if parts.len() != 2 {
        panic!("Input format is incorrect, expected format: number(base)");
    }
    let num = parts[0];
    let from_base_str = parts[1].trim_end_matches(')');
    let from_base = u32::from_str(from_base_str).expect("Invalid base");

    if from_base < 2 || from_base > 16 {
        panic!("Original base must be between 2 and 16");
    }

    // 将原始数字转换为10进制
    let decimal = isize::from_str_radix(num, from_base).expect("Invalid number");

    // 将10进制数字转换为目标进制
    let mut result = String::new();
    let mut num = decimal;
    while num > 0 {
        let remainder = num % to_base as isize;
        result.push_str(&digit_to_char(remainder));
        num /= to_base as isize;
    }

    // 翻转结果
    if result.is_empty() { "0".to_string() } else { result.chars().rev().collect() }
}

/// 将数字转换为对应的字符
fn digit_to_char(digit: isize) -> String {
    match digit {
        0..=9 => (b'0' + digit as u8) as char,
        10..=15 => (b'a' + (digit - 10) as u8) as char,
        _ => panic!("Digit must be between 0 and 15"),
    }.to_string()
}